#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int g_count;

int getRand(int num)
{
    g_count++;
    if(num <= 0) return 0;

    return rand() % num + 1;    
}

void swap(int *a, int *b);
void quicksort(int *array, int maxlen, int begin, int end);
int exists(int *p, int len, int value);

int main(int argc, char *argv[])
{
    int i, j, k;
    int red[7];
    srand(time(NULL));

    g_count = 0;
    for (j = 0; j < 10; j++) {
        for(i = 0; i < 7; i++)
            red[i] = 0;

        for(i = 0; i < 6; i++) {
            k = getRand(33);
            while(exists(red, 6, k)) {
                k = getRand(33);
            }
            red[i] = k;
        }

        red[6] = getRand(16) + 1;
        quicksort(red, 33, 0, 5);
        for(i = 0; i < 7; i++) {
            printf("%2d ", red[i]);
       }
        printf("\n");
    }
    printf("g_count = %d\n", g_count);

    return 0;
}

void quicksort(int *array, int maxlen, int begin, int end)
{
    int i, j;

    if(begin < end) {
        i = begin + 1;
        j = end;

        while(i < j) {
            if(array[i] > array[begin]) {
                swap(&array[i], &array[j]);
                j--;
            }
            else {
                i++;
            }
        }

        if(array[i] >= array[begin]) {
            i--;
        }

        swap(&array[begin], &array[i]);

        quicksort(array, maxlen, begin, i);
        quicksort(array, maxlen, j, end);
    }
}

void swap(int *a, int *b)
{
    int temp;

    temp = *a;
    *a = *b;
    *b = temp;
}

int exists(int *p, int len, int value)
{
    int i, flag = 0;
    for(i = 0; i < len; i++) {
        if(p[i] == value) {
            flag = 1;
            break;
        }
    }

    return flag;
}
